//一个非常简单的store的示例
import Vue from 'vue'
import Vuex from 'vuex'
import loginApi from '@/api/login.js'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
		token: '', 
		hasLogin: false, // 是否登录
		user:{}, // 用户信息
		// 长辈模式默认为true 开启则为false
		isNormalX: true
    },
    mutations: {
		// 设置token
		setToken(state,token){
		    console.info('_setToken_',token)
		    state.token = token;
		},
		// 设置登录信息
		setUser(state,user){
		    console.info('_setUser_',user)
		    state.user = user;
		    state.hasLogin = true;
		},
		clearUser(state){
		    console.info('_clearUser_')
		    state.user = null;
		    state.hasLogin = false;
		},
		//更新state数据
		setStateAttr(state, param) {
			if (param instanceof Array) {
				for (let item of param) {
					state[item.key] = item.val;
				}
			} else {
				state[param.key] = param.val;
			}
		}
    },
	// 3. actions 通常跟api接口打交道
	actions:{
	    Login(store){
	      return new Promise((resolve, reject) => {
	        if (state.hasLogin) { //已经登录
	            resolve(state.user)
	        } else {
	          uni.login({
	            success: async res => {
	              const response = await loginApi.lgoin({code:res.code,origin:'xcx'})
	              const {code,data} = response
	              if(code==20000){
	                  console.info('登录成功')
	                  store.commit('setToken', data.token)
	                  resolve()
	              }else{
	                uni.showToast({ title: '登录异常', icon: 'none' })
	              }
	            }
	          })
	        }
	      });
	    },
	    Logout: function(store) {
	      return new Promise(function (resolve, reject) {
	          store.commit('clearUser');
	          resolve()
	      });
	    }
	}
})
export default store